﻿using Npgsql;

namespace Infrastructure.Persistence;

public class PostgreSqlDataProvider : BoilerplateDataProvider
{
    public override bool CreateDatabaseIfNotExists(string connectionString)
    {
        (connectionString, var databaseName) = GetConnectionStringFormat(connectionString);

        // 检查数据库是否已经存在
        if (DatabaseExists(databaseName, connectionString))
        {
            Console.WriteLine($"Database '{databaseName}' already exists.");
            return false;
        }

        var npgsqlConnection = new NpgsqlConnection(connectionString);
        npgsqlConnection.Open();

        var command = npgsqlConnection.CreateCommand();
        command.CommandText = $"CREATE DATABASE {databaseName};";
        command.ExecuteNonQuery();

        Console.WriteLine($"Database '{databaseName}' created successfully.");

        return true;
    }

    public override bool DatabaseExists(string databaseName, string connectionString)
    {
        string query = $"SELECT COUNT(*) FROM pg_catalog.pg_database WHERE datname='{databaseName}';";

        using NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connectionString);
        npgsqlConnection.Open();

        using NpgsqlCommand command = npgsqlConnection.CreateCommand();
        command.CommandText = query;

        long? count = (long?)command.ExecuteScalar();

        return count.HasValue && count.Value > 0;
    }
}
